<template>
  <div class="shopping-cart">
    <h1>购物车</h1>
    <ul>
      <li v-for="item in cartItems" :key="item.id">
        {{ item.name }} - ￥{{ item.price }} -数量:{{ item.quantity }}
        <button @click="updateQuantity(item.id, item.quantity + 1)">+</button>
        <button @click="updateQuantity(item.id, item.quantity - 1)">-</button>
      </li>
    </ul>
    <div class="total">
      总价：￥{{ totalPrice }}
    </div>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex';

export default {
  computed: {
    ...mapGetters(['cartItems', 'totalPrice'])
  },
  methods: {
    ...mapMutations(['add_item', 'remove_item', 'update_item']),
    updateQuantity(id, quantity) {
      if (quantity < 1) {
        this.remove_item(id);
      } else {
        this.update_item({ id, quantity });
      }
    }
  }
};
</script>

<style scoped>
/*  */
</style>